const { contextBridge, ipcRenderer } = require('electron');
let dataList = [];

contextBridge.exposeInMainWorld('electronAPI', {
    // 通知主进程修改大小
    setSize: (setObj) => ipcRenderer.send('setSize', setObj),
    // 通知主进程读取文件
    readFile: () => ipcRenderer.send('readFile'),
    // 打开浏览器链接
    openUrl: (setupObj) => ipcRenderer.send('openUrl', {
        ...setupObj
    }),
    /** 
     *  通知主进程过滤文件
     *  @param {object} setupObj 设置对象
     */
    filterFile: (setupObj) => ipcRenderer.send('filterFile', {
        ...setupObj
    }),
    /**
     * 通知主进程同步禅道
     */
    getChanDaoData: (setupObj) => ipcRenderer.send('getChanDaoData', {
        ...setupObj
    }),
    /**
     * 添加订阅
     */
    watchPublicInfo: (setupObj) => ipcRenderer.send('watchPublicInfo', {
        ...setupObj
    }),
    /**
     * 通知主进程修改文件
     * @param {object} setupObj 设置对象
     */
    setupFile: (setupObj) => ipcRenderer.send('setupFile', {
        ...setupObj,
        dataList
    }),
    /**
     * 返回文件数据
     * @param {Object} event
     * @param {Array} data 表格数据
     */
    returnFileData: () => ipcRenderer.on('returnFileData', (event, data) => {
        dataList = data;
        const completelist = [];
        const unCompletelist = [];
        data[0].data.forEach(item => {
            if (item[3]) {
                completelist.push(item)
            } else {
                unCompletelist.push(item)
            }
        });
        // 按时间排序
        unCompletelist.sort((a, b) => { return new Date(a[2]) - new Date(b[2]) })
        // 未完成数据按照优先级排序
        unCompletelist.sort((a,b) => Number(b[6] || 0) - Number(a[6] || 0));
        document.getElementById("tbodyDataBox").innerHTML = getTemplateStr(unCompletelist);
        document.getElementById("tbodyCompleteDataBox").innerHTML = getTemplateStrByComplete(completelist.sort((a, b) => { return new Date(a[2]) - new Date(b[2]) }));
        // document.getElementById("loadingBox").classList.remove("isLoading");
    }),
    /**
     * 关闭loading
     */
    closeLoading: () => ipcRenderer.on('closeLoading', (event, data) => {
        document.getElementById("loadingBox").classList.remove("isLoading");
    }),
    /**
     * 弹窗错误提示
     */
    errorLoading: () => ipcRenderer.on('errorLoading', (event, data) => {
        document.getElementById("loadingBox").classList.remove("isLoading");
        document.getElementById("errorLoading").style.display = "flex";
    }),
    watchPublicInfoUpdate: () => ipcRenderer.on('watchPublicInfoUpdate', (event, data) => {
        const { list } = data;
        document.getElementById("tbodySubscribeBox").innerHTML = getTemplateStrBySubscribe(list);
    }),
    watchPublicInfoTip: () => ipcRenderer.on('watchPublicInfoTip', (event, data) => {
        const { successObj } = data;
        alert(`项目：${successObj.pname}，学校：${successObj.cname}，打包成功。`);
    })
})
/**
 * @param {Array} dataArray 数据数组
 * @returns {string} dom字符结构
 */
function getTemplateStr(dataArray, type) {
    console.log(dataArray)
    let trStr = "";
    dataArray.forEach(rowItem => {
        let innerStr = "";
        ['', '', '', ''].forEach((item, index) => {
            const colItem = rowItem[index];
            if (index === 1) {
                innerStr += `
                    <td style="${rowItem[6] == 1 ? 'background-color: skyblue;':''}" title="${colItem || ''}" onclick="window.electronAPI.openUrl({url:'${colItem}'})">
                        <span>${colItem || ''}</span>
                    </td>
                `
            } else {
                innerStr += `
                    <td style="${rowItem[6] == 1 ? 'background-color: skyblue;':''}" title="${colItem || ''}">
                        <span>${colItem || ''}</span>
                    </td>
                `
            }
        })
        trStr += `
            <tr style="display:${rowItem[5] ? 'table-row' : 'none'}">
                ${innerStr}
                <td>
                    <div style="max-height:50px;overflow-y:auto">
                        <span style="margin:5px 0;background:skyblue" onclick="editFn('${rowItem}')">编辑</span>
                        <span style="margin:5px 0;background:skyblue" onclick="completeFn(${rowItem[4]})">完成</span>
                        <span style="margin:5px 0;background:skyblue" onclick="upHierarchicalStructureFn(${rowItem[4]})">${rowItem[6] ? '取优':'优先'}</span>
                        <span style="margin:5px 0 0 0;background:red" onclick="delFn(${rowItem[4]})">删除</span>
                    </div>
                </td>
            </tr>
        `
    })
    return trStr
}
/**
 * @param {Array} dataArray 数据数组
 * @returns {string} dom字符结构
 */
function getTemplateStrByComplete(dataArray, type) {
    let trStr = "";
    dataArray.forEach(rowItem => {
        let innerStr = "";
        ['', '', '', ''].forEach((item, index) => {
            const colItem = rowItem[index];
            if (index === 1) {
                innerStr += `
                    <td style="${rowItem[6] == 1 ? 'background-color: skyblue;':''}" title="${colItem || ''}" onclick="window.electronAPI.openUrl({url:'${colItem}'})">
                        <span>${colItem || ''}</span>
                    </td>
                `
            } else {
                innerStr += `
                    <td style="${rowItem[6] == 1 ? 'background-color: skyblue;':''}" title="${colItem || ''}">
                        <span>${colItem || ''}</span>
                    </td>
                `
            }
        })
        trStr += `
            <tr style="display:${rowItem[5] ? 'table-row' : 'none'}">
                ${innerStr}
                <td>
                    <div style="max-height:50px;overflow-y:auto">
                        <span style="margin:5px 0;background:skyblue" onclick="editFn('${rowItem}')">编辑</span>
                        <span style="margin:5px 0;background:skyblue" onclick="resetFn(${rowItem[4]})">回退</span>
                        <span style="margin:5px 0 0 0;background:red" onclick="delFn(${rowItem[4]})">删除</span>
                    </div>
                </td>
            </tr>
        `
    })
    return trStr
}

function getTemplateStrBySubscribe(dataArray, type) {
    let trStr = "";
    console.log(dataArray)
    dataArray.forEach(rowItem => {
        trStr += `
            <td>
                <span>${rowItem.id || ''}</span>
            </td>
            <td>
                <span>${rowItem.cname || ''}</span>
            </td>
            <td>
                <span>${rowItem.pname || ''}</span>
            </td>
        `
    })
    return trStr
}